In [1]:
sentence = 'the quick brown fox jumps over the lazy dog'
words = sentence.split()
word_lengths = [len(word) for word in words if 'the' != word]
print(word_lengths)
In [2]:
def foo(first, second, third, *therest):
print('First: %s' % first)
print('Second: %s' % second, end=' or ')
print('Second: {}'.format(second)) # more modern approach
print('Third: %s' % third)
print('And all the rest... %s' % list(therest))
return
print(foo(1,2,3,4,5))
In [3]:
def bar(first, second, third, **options):
print('Options is a variable of {}.'.format(type(options)))
if 'sum' == options.get('action'):
print('The sum is: %d' % (first + second + third))
if 'first' == options.get('number'):
return first
result = bar(1, 2, 3, action='sum', number='first')
print('Result: %d' % result)
In [4]:
myExp = r'^(From|To|Cc).*?python-list@python.org'
import re
pattern = re.compile(myExp)
result = re.match(pattern, 'From sometextpython-list@python.org and some more')
if result:
print(result)
print('Whole result:', result.group(0), sep='\t')
print('First part:', result.group(1), sep='\t')
In [5]:
a = set(('Jake', 'John', 'Eric')) # generate a set from a tuple
b = set(['John', 'Jill']) # or generate a set from a list
print(a.intersection(b)) # in both sets
print(a.difference(b)) # in a but not in b
print(a.symmetric_difference(b)) # distinct
print(a.union(b)) # joined set
In [6]:
import json
json_string = json.dumps([1, 2, 3, 'a', 'b', 'c'])
print(json_string)
print(json.loads(json_string))
json_string = json.dumps([1, 2, 3, 'a', 'b', 'c'], indent=2, sort_keys=True, separators=(',', ':'))
print(json_string)
write JSON to and from a file
In [7]:
writeFp = open('config.json', 'w')
json.dump({'b':1, 'a':2}, writeFp, sort_keys=True)
writeFp.close()
readFp = open('config.json', 'r')
for line in readFp:
print(line)
readFp.close()
# separators without spaces reduce json file size
print(json.dumps({'b':1, 'a':2}, sort_keys=True, separators=(',', ':')))
Using cPickle, Python's proprietary object serialization method. With pickle, objects can be serialized.
Properties of pickle serialization: pickle = {binary: true, humanReadable: false, pythonSpecific: true, serializeCustomClasses: true}
In [8]:
import pickle # or cPickle for a faster implementation
pickled_string = pickle.dumps([1, 2, 3, 'a', 'b', 'c'])
print(pickle.loads(pickled_string), end='\n\n')
class MyTestClass:
def say(self):
return 'hello'
pickled_string = pickle.dumps(MyTestClass())
print('Pickled:\t{}\nUnpickled:\t{}\nInstance call:\t{}'.format(
pickled_string, pickle.loads(pickled_string), pickle.loads(pickled_string).say()
)
)